//
//  Routine.m
//  Together_iOS
//
//  Created by applex on 14-3-1.
//  Copyright (c) 2014年 QIU Shuang. All rights reserved.
//

#import "Plan.h"
#import "Stop.h"
#import "User.h"
#import "TogetherHttpClient.h"
#import "TogetherUtils.h"

#import <SSToolkit/SSCategories.h>

#import "AFNetworking.h"


@implementation Plan

@dynamic remoteID;
@dynamic status;
@dynamic date;
@dynamic shared;
@dynamic createdTime;
@dynamic planDate;
@dynamic owner;
@dynamic stops;
@dynamic regions;
@dynamic rating;


- (NSArray *)stops {
    NSOrderedSet *temp;
    [self willAccessValueForKey:@"stops"];
    temp = [self primitiveValueForKey:@"stops"];
    [self didAccessValueForKey:@"stops"];
    return [temp array];
}

- (void)unpackDictionary:(NSDictionary *)dictionary {
    [super unpackDictionary:dictionary];
    self.status = @([dictionary[@"status"] intValue]);
    self.date = [NSDate dateWithTimeIntervalSince1970:[dictionary[@"date"] longLongValue] / 1000];
    self.shared = @([dictionary[@"shared"] intValue]);
    self.createdTime = [NSDate dateWithTimeIntervalSince1970:[dictionary[@"create_time"] longLongValue] / 1000];
    self.planDate = [NSDate dateWithTimeIntervalSince1970:[dictionary[@"plan_date"] longLongValue] / 1000];
    self.regions = dictionary[@"regions"];
    self.rating = @([dictionary[@"rating"] integerValue]);
    
    NSArray *stops = [dictionary objectForKey:@"stops"];
    for (NSDictionary *s in stops) {
        Stop *stop = [Stop objectWithDictionary:s];
        [self addStopsObject:stop];
    }
    
    if ([dictionary[@"owner_id"] intValue] != 0) {
        self.owner = [User objectWithRemoteID:@([dictionary[@"owner_id"] integerValue])];
    }
}

- (BOOL)isShared {
    return [self.shared intValue] == 1;
}


+ (NSArray *)defaultSortDescriptors {
    return [NSArray arrayWithObjects:
            [NSSortDescriptor sortDescriptorWithKey:@"owner" ascending:NO],
            [NSSortDescriptor sortDescriptorWithKey:@"createdTime" ascending:YES],
            nil];
}


- (void)saveToRemoteWithSuccess:(void(^)())successBlock failure:(void(^)(NSError *error))failureBlock {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSString *requestUrl;
    NSDictionary *parameters = @{@"plan": [TogetherUtils jsonStringFromData:self.packedDictionary]};
    
    if (self.isRemote) {
        requestUrl = [[TogetherHttpClient serverAddress] stringByAppendingFormat:@"/plans/%@", self.remoteID];
        [manager PUT:requestUrl
          parameters:parameters
             success:^(AFHTTPRequestOperation *operation, id responseObject) {
                 if (successBlock) {
                     successBlock();
                 }
             }
             failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                 if (failureBlock) {
                     failureBlock(error);
                 }
             }];
    } else {
        requestUrl = [[TogetherHttpClient serverAddress] stringByAppendingString:@"/plans"];
        [manager POST:requestUrl
          parameters:parameters
             success:^(AFHTTPRequestOperation *operation, id responseObject) {
                 if (successBlock) {
                     successBlock();
                 }
             }
             failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                 if (failureBlock) {
                     failureBlock(error);
                 }
             }];

    }
}


+ (void)fetchFromServerByRemoteID:(NSNumber *)remoteID success:(void(^)(Plan *plan))successBlock failure:(void(^)(NSError *error))failureBlock {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSString *requestUrl = [[TogetherHttpClient serverAddress] stringByAppendingFormat:@"/plans/%@", remoteID];
    [manager GET:requestUrl
      parameters:nil
         success:^(AFHTTPRequestOperation *operation, id responseObject) {
             NSDictionary *dic = (NSDictionary *)responseObject;
             Plan *p = [Plan objectWithDictionary:dic[@"plan"]];
             [p save];
             
             if (successBlock) {
                 successBlock(p);
             }
         }
         failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             NSLog(@"[error]%@", error);
         }];
}


+ (void)planListFromServerWithSuccess:(void(^)(Plan *plan))successBlock failure:(void(^)(NSError *error))failureBlock {
    
}


- (NSDictionary *)packedDictionary {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    if (self.remoteID && [self.remoteID intValue] != 0) {
        [dic setObject:self.remoteID forKey:@"id"];
    }
    if (self.status) {
        [dic setObject:self.status forKey:@"status"];
    }
    if (self.date) {
        [dic setObject:@((long long int)([self.date timeIntervalSince1970] * 1000)) forKey:@"date"];
    }
    if (self.shared) {
        [dic setObject:@([self.shared intValue] == 1) forKey:@"shared"];
    }
    if (self.createdTime) {
        [dic setObject:@((long long int)([self.createdTime timeIntervalSince1970] * 1000)) forKey:@"create_time"];
    }
    if (self.planDate) {
        [dic setObject:@((long long int)([self.planDate timeIntervalSince1970] * 1000)) forKey:@"plan_date"];
    }
    if (self.owner) {
        [dic setObject:self.owner.remoteID forKey:@"owner_id"];
    }
    if (self.rating) {
        [dic setObject:self.rating forKey:@"rating"];
    }
    if (self.regions) {
        [dic setObject:self.regions forKey:@"regions"];
    }
    NSMutableArray *array = [NSMutableArray array];
    NSArray *sortedStops = [self.stops sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"startTime" ascending:YES]]];
    for (Stop *s in sortedStops) {
        [array addObject:[s packedDictionary]];
    }
    
    [dic setObject:array forKey:@"stops"];
    return dic;
}

@end
